Crypto : Crypto library

更新时间:
2024-03-13
下载文档

Crypto : Crypto library

crypto is an algorithm library for various encryption, decryption, hashing, and digital signature verification.

Currently supports MD5, RIPEMD160, SHA-1, SHA-256, SHA-384, SHA-512 hash algorithm, supports RAS signature and verify, supports TLS Cipher encryption and decryption.

User can use the following code to import the crypto module.

var crypto = require('crypto');

Support

The following shows crypto module APIs available for each permissions.

 User ModePrivilege Mode
crypto.getHashes
crypto.getCiphers
crypto.createHash
crypto.createHmac
crypto.createVerify
crypto.createSign
crypto.createCipheriv
crypto.createDecipheriv
crypto.generateKeyPair
crypto.createPrivateKey
crypto.createPublicKey
crypto.privateDecrypt
crypto.privateEncrypt
crypto.publicDecrypt
crypto.publicEncrypt
crypto.randomBytes
crypto.randomFill
crypto.randomInt
crypto.randomUUID
crypto.creditCertNum 
crypto.creditCertInfo 
crypto.scrypt
hash.update
hash.digest
hash.digestFile
hash.restart
hmac.update
hmac.digest
hmac.digestFile
hmac.restart
verify.update
verify.verify
verify.verifyFile
verify.restart
sign.update
sign.sign
sign.signFile
sign.restart
key.export
key.encrypt
key.decrypt
key.options
cipher.final
cipher.update
cipher.setAAD
cipher.setAutoPadding
cipher.getAuthTag
cipher.restart
decipher.final
decipher.update
decipher.setAAD
decipher.setAutoPadding
decipher.setAuthTag
decipher.restart

Crypto Information

crypto.getHashes()

  • Returns: {Array} A supported hash algorithm list array.

Get the currently supported hash algorithm list.

Example

console.log(crypto.getHashes());

crypto.getCiphers()

  • Returns: {Array} A supported Cipher algorithm list array.

Get the currently supported cipher algorithm list.

Example

console.log(crypto.getCiphers());

Crypto Creator

crypto.createHash(hashtype[, hmackey])

  • hashtype {String} Type of hash algorithm.
  • hmackey {String} | {Buffer} Specify HMAC key if HMAC encoding is used. default: undefined, do not use hmac.
  • Returns: {Object} Hash object.

Create a hash algorithm object. Current support hash algorithms include: 'md5', 'ripemd160', 'sha1', 'sha256', 'sha384', 'sha512'.

Example

var hash = crypto.createHash('md5');
var hash = crypto.createHash('sha1');
var hash = crypto.createHash('sha1', '1234567890');
var hash = crypto.createHash('sha256');

crypto.createHmac(hashtype, hmackey)

  • hashtype {String} Type of hash algorithm.
  • hmackey {String} | {Buffer} Specify HMAC key if HMAC encoding is used.
  • Returns: {Object} Hash object.

Create a hash algorithm with HMAC object. Current support hash algorithms include: 'md5', 'ripemd160', 'sha1', 'sha256', 'sha384', 'sha512'.

Example

var hmac = crypto.createHmac('sha1', '1234567890');

crypto.createVerify(hashType[, hmackey])

  • hashType {String} Hash type of the signature: 'sha1', 'sha256', 'sha384' or 'sha512'.
  • hmackey {String} | {Buffer} Specify HMAC key if HMAC encoding is used. default: undefined, do not use hmac.
  • Returns: {Object} Verify object.

Creates and returns a Verify object.

Example

var verify = crypto.createVerify('sha256');
var verify = crypto.createVerify('sha256', 'abcdefg');

crypto.createSign(hashType[, hmackey])

  • hashType {String} Hash type of the signature: 'sha1', 'sha256', 'sha384' or 'sha512'.
  • hmackey {String} | {Buffer} Specify HMAC key if HMAC encoding is used. default: undefined, do not use hmac.
  • Returns: {Object} Signature object.

Creates and returns a Signature object.

Example

var sign = crypto.createSign('sha256');
var sign = crypto.createSign('sha256', 'abcdefg');

crypto.createCipheriv(algorithm, key, iv[, options])

  • algorithm {String} Cipher algorithm.
  • key {Buffer} | {String} Cipher key.
  • iv {Buffer} | {String} Cipher initialization vector.
  • options {Object} Other options. default: no options.
  • Returns: {Object} Cipher object.

Create and return a Cipher object using the given algorithm, key and initialization vector(iv).

The option object can contain the following member:

  • authTagLength {Integer} Specify the length of the authentication tag in bytes. (Only for GCM mode)

The currently supported algorithms are as follows: 'aes-128-ecb', 'aes-192-ecb', 'aes-256-ecb', 'aes-128-cbc', 'aes-192-cbc', 'aes-256-cbc', 'aes-128-cfb128', 'aes-192-cfb128', 'aes-256-cfb128', 'aes-128-ctr', 'aes-192-ctr', 'aes-256-ctr', 'aes-128-gcm', 'aes-192-gcm', 'aes-256-gcm', 'aes-128-ccm', 'aes-192-ccm', 'aes-256-ccm', 'camellia-128-ecb', 'camellia-192-ecb', 'camellia-256-ecb', 'camellia-128-cbc', 'camellia-192-cbc', 'camellia-256-cbc', 'camellia-128-cfb128', 'camellia-192-cfb128', 'camellia-256-cfb128', 'camellia-128-ctr', 'camellia-192-ctr', 'camellia-256-ctr', 'camellia-128-gcm', 'camellia-192-gcm', 'camellia-256-gcm', 'camellia-128-ccm', 'camellia-192-ccm', 'camellia-256-ccm', 'des-ecb', 'des-cbc', 'des-ede-ecb', 'des-ede-cbc', 'des-ede3-ecb', 'des-ede3-cbc'.

Example

const key = 'keykeykeykeykeykeykeykey';
const nonce = crypto.randomBytes(12);

const cipher = crypto.createCipheriv('aes-192-gcm', key, nonce, {
  authTagLength: 16
});

crypto.createDecipheriv(algorithm, key, iv[, options])

  • algorithm {String} Decipher algorithm.
  • key {Buffer} | {String} Decipher key.
  • iv {Buffer} | {String} Decipher initialization vector.
  • options {Object} Other options. default: no options.
  • Returns: {Object} Decipher object.

Create and return a Decipher object using the given algorithm, key and initialization vector(iv).

The option object can contain the following member:

  • authTagLength {Integer} Specify the length of the authentication tag in bytes. (Only for GCM mode)

Example

const key = 'keykeykeykeykeykeykeykey';
const nonce = crypto.randomBytes(12);

const decipher = crypto.createDecipheriv('aes-192-gcm', key, nonce, {
  authTagLength: 16
});

crypto.generateKeyPair(type[, opt])

  • type {String} Must be 'rsa' or 'ec'.
  • opt {Object} Key options.
  • Returns: {Object} Pair of keys.

Generates a new asymmetric key pair of the given type. RSA, EC are currently supported.

The opt object can contain the following members:

  • modulusLength {Integer} Key size in bits.

The returned object contains the following members:

  • publicKey {String} PEM formate public key string.
  • privateKey {String} PEM formate private key string.

Example

const { publicKey, privateKey } = crypto.generateKeyPair('rsa', { modulusLength: 2048 });
console.log(publicKey, privateKey);

crypto.createPrivateKey(privateKey[, passwd])

  • privateKey {String} Private key string.
  • passwd {String} Private key passwd.
  • Returns: {KeyObject} Private key object.

Check whether the private key is valid, and return this private key if it is valid.

crypto.createPublicKey(privateOrPublicKey[, passwd])

  • privateKey {String} Private key string.
  • passwd {String} Private key passwd.
  • Returns: {KeyObject} Public key object.

Creates and returns a public key object.

Example

var publicKey = crypto.createPublicKey(publicKey);

crypto.privateDecrypt(privateKey, buffer)

  • privateKey {KeyObject} | {String} Private key.
  • buffer {Buffer} Data that needs to be decrypted.
  • Returns: {Buffer} Decrypted data.

Use private key for data decryption.

crypto.privateEncrypt(privateKey, buffer)

  • privateKey {KeyObject} | {String} Private key.
  • buffer {Buffer} Data that needs to be encrypted.
  • Returns: {Buffer} Encrypted data.

Use private key for data encryption.

crypto.publicDecrypt(publicKey, buffer)

  • publicKey {KeyObject} | {String} Public key.
  • buffer {Buffer} Data that needs to be decrypted.
  • Returns: {Buffer} Decrypted data.

Use public key for data decryption.

crypto.publicEncrypt(publicKey, buffer)

  • publicKey {KeyObject} | {String} Public key.
  • buffer {Buffer} Data that needs to be encrypted.
  • Returns: {Buffer} Encrypted data.

Use public key for data encryption.

Example

var { publicKey, privateKey } = crypto.generateKeyPair('rsa', { modulusLength: 2048 });

privateKey = crypto.createPrivateKey(privateKey);
publicKey = crypto.createPublicKey(publicKey);

// Private Key Encrypt
var endata = crypto.privateEncrypt(privateKey, new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]));
console.log(endata.toString('hex'));

// Public Key Decrypt
var dedata = crypto.publicDecrypt(publicKey, endata);
console.log(dedata.toString('hex'));

Example

var { publicKey, privateKey } = crypto.generateKeyPair('rsa', { modulusLength: 2048 });

privateKey = crypto.createPrivateKey(privateKey);
publicKey = crypto.createPublicKey(publicKey);

// Public Key Encrypt
var endata = crypto.publicEncrypt(publicKey, new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]));
console.log(endata.toString('hex'));

// Private Key Decrypt
var dedata = crypto.privateDecrypt(privateKey, endata);
console.log(dedata.toString('hex'));

crypto.randomBytes(size)

  • size {Integer} Buffer size (MAX: 256KB).
  • Returns: {Buffer} Buffer object.

Create a buffer of the specified size and fill it with random data.

Example

var randBuf = crypto.randomBytes(16);

crypto.randomFill(buffer[, offset][, size])

  • buffer {Buffer} Buffer for random data.
  • offset {Integer} Buffer offset. default:0.
  • size {Integer} Random data length limit. default:buffer.length.
  • Returns: {Buffer} The object passed as buffer argument.

This function is similar to crypto.randomBytes() but requires the first argument to be a Buffer that will be filled.

Example

var buf = new Buffer(16);
crypto.randomFill(buf);

crypto.randomInt([min, ]max[, callback])

  • min {Integer} Minimum. default: 0.
  • max {Integer} Maximum.
  • callback {Function} Callback.
    • error {Error} Specify error.
    • n {Integer} Random integer.
  • Returns: {Undefined | Integer} If no callback is specified, a random integer is returned.

Return a random integer n such that min <= n < max. min and max must be safe integers. EdgerOS 1.7.9 and later support.

crypto.randomUUID()

  • Returns: {String} Randomly generated UUID string.

Generate a UUID string. EdgerOS 1.7.9 and later support.

Example

var uuid = crypto.randomUUID();
// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

crypto.creditCertNum()

  • Returns: {Integer} Number of certificates.

Get the total number of current credit certificates in the system.

crypto.creditCertInfo(index)

  • index {Integer} Certificate index.
  • Returns: {Object} Credit certificate information.

Get the specified credit certificate information. The return value contains the following members:

  • version {Integer} Certificate version: 1, 2, 3.
  • serial {String} Certificate serial number.
  • issuer {String} Issuer of this certificate.
  • subject {String} Subject name.
  • validFrom {Date} Validity time begin.
  • validTo {Date} Validity time to.
  • sigAlgorithm {String} Signature algorithm.
  • keySize {Integer} Key size bits.
  • basicConstraints {Object} Basic constraints.
    • CA {Boolean} Is it a CA certificate.
    • maxPath {Integer} Max path length.
  • keyUsage {Object} Key usage.
    • digitalSignature {Boolean} Digital signature.
    • nonRepudiation {Boolean} Non repudiation.
    • keyEncipherment {Boolean} Key encipherment.
    • dataEncipherment {Boolean} Data encipherment.
    • keyAgreement {Boolean} Key agreement.
    • keyCertSignature {Boolean} key cert signature.
    • crlSignature {Boolean} Crl signature.
    • encipherOnly {Boolean} Encipher only.
    • decipherOnly {Boolean} Decipher only.
  • info {String} All information string.

Example

var total = crypto.creditCertNum();
for (var i = 0; i < total; i++) {
  console.log(crypto.creditCertInfo(i).info);
}

crypto.scrypt(passwd, salt, keylen)

  • passwd {String} | {Buffer} Password.
  • salt {String} | {Buffer} Salt.
  • keylen {Integer} Key length in bytes.
  • Returns: {Buffer} Key buffer.

Scrypt is a password-based key derivation function, the purpose is to make brute force cracking impossible. The salt should be as unique as possible. It is recommended that the salt value be random and at least 16 bytes long.

Example

var salt = crypto.randomBytes(16);
var key = crypto.scrypt('edgeros', salt, 16);
console.log(key.toString('hex'));

Hash Object

Hash inherits from stream.Transform class, you can use stream to perform hash operation.

Example

const crypto = require('crypto');
const hash = crypto.createHash('sha256');

hash.on('readable', () => {
  // Only one element is going to be produced by the
  // hash stream.
  const data = hash.read();
  if (data) {
    console.log(data.toString('hex'));
    // Prints:
    // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
  }
});

hash.write('some data to hash');
hash.end();

hash.update(data)

  • data {Buffer} | {String} Updates the object with the data. If there is already data in the object, concatenates them.
  • Returns: {Object} This hash object. EdgerOS 1.5.3 and later.

Updates the Hash object with the given data.

hash.digest([encoding])

  • encoding {String} Encodes the result of the hashing to the given format. Can be {'hex' | 'base64'}. If no encoding is given, or the given encoding doesn't match the known formats, returns the raw hash in a Buffer. default: return buffer.

Returns an encoded hash of the input data as a string or Buffer.

Example

var crypto = require('crypto');

var myData = 'Some data to hash';
var myHashObj = crypto.createHash('sha1');
myHashObj.update(myData);
var myHash = myHashObj.digest('hex');

hash.digestFile(file[, encoding])

  • file {String} A file that needs to calculate a hash value.
  • encoding {String} Encodes the result of the hashing to the given format. Can be {'hex' | 'base64'}. If no encoding is given, or the given encoding doesn't match the known formats, returns the raw hash in a Buffer. default: return buffer.

Returns an encoded hash of the input data as a string or Buffer.

Example

var myHashObj = crypto.createHash('sha1');
var myHash = myHashObj.digestFile('./test.txt', 'hex');

hash.restart()

Reset the internal state of the hash object, and the hash object can perform update() and digest() operations again.

Hmac Object

Hmac inherits from stream.Transform class, you can use stream to perform hash operation.

Example

const crypto = require('crypto');
const hmac = crypto.createHmac('sha256', 'a secret');

hmac.on('readable', () => {
  // Only one element is going to be produced by the
  // hash stream.
  const data = hmac.read();
  if (data) {
    console.log(data.toString('hex'));
    // Prints:
    // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
  }
});

hmac.write('some data to hash');
hmac.end();

hmac.update(data)

  • data {Buffer} | {String} Updates the object with the data. If there is already data in the object, concatenates them.
  • Returns: {Object} This hmac object. EdgerOS 1.5.3 and later.

Updates the Hmac object with the given data.

hmac.digest([encoding])

  • encoding {String} Encodes the result of the hashing to the given format. Can be {'hex' | 'base64'}. If no encoding is given, or the given encoding doesn't match the known formats, returns the raw hash in a Buffer. default: return buffer.

Returns an encoded hash of the input data as a string or Buffer.

Example

var crypto = require('crypto');

var myData = 'Some data to hash';
var myHashObj = crypto.createHmac('sha1', 'hmackey');
myHashObj.update(myData);
var myHash = myHashObj.digest('hex');

hmac.digestFile(file[, encoding])

  • file {String} A file that needs to calculate a hash value.
  • encoding {String} Encodes the result of the hashing to the given format. Can be {'hex' | 'base64'}. If no encoding is given, or the given encoding doesn't match the known formats, returns the raw hash in a Buffer. default: return buffer.

Returns an encoded hash of the input data as a string or Buffer.

Example

var myHashObj = crypto.createHmac('sha1', 'hmackey');
var myHash = myHashObj.digestFile('./test.txt', 'hex');

hmac.restart()

Reset the internal state of the hmac object, and the hmac object can perform update() and digest() operations again.

Verify Object

Verify inherits from stream.Writable class, you can use stream to perform verify operation.

Example

const crypto = require('crypto');

const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', {
  namedCurve: 'sect239k1'
});

const sign = crypto.createSign('SHA256');
sign.write('some data to sign');
sign.end();
const signature = sign.sign(privateKey, 'hex');

const verify = crypto.createVerify('SHA256');
verify.write('some data to sign');
verify.end();
console.log(verify.verify(publicKey, signature, 'hex'));
// Prints: true

verify.update(data)

  • data {Buffer} | {String} Updates the object with the data. If there is already data in the object, concatenates them.
  • Returns: {Object} This verify object. EdgerOS 1.5.3 and later.

Updates the Verify object with the given data.

Example

var crypto = require('crypto');
var myVerifyObject = crypto.createVerify('sha256');

myVerifyObject.update('This data should be verified');
myVerifyObject.update('\nAnd this belongs there too.');

verify.verify(publicKey, signature[, signatureEncoding])

  • publicKey {String} | {Buffer} | {KeyObject} A valid RSA Public key.
  • signature {String} | {Buffer} Signature.
  • signatureEncoding {String} Signature encoding. default: base64.
  • Returns: {Boolean} true if the verification succeeds, false otherwise.

Verifies the signature against the publicKey using the data added with verify.update().

Example

var crypto = require('crypto');

var myVerifyObject = crypto.createVerify('sha256');
var myKey = getPublicKeySomehow();
var myData = getSomeStringToVerify();
var mySignature = getSignatureSomehow();

myVerifyObject.update(myData);

var success = myVerifyObject.verify(myKey, mySignature);
if (!success) {
  throw new Error('Invalid signature!');
}

verify.verifyFile(file, publicKey, signature[, signatureEncoding])

  • file {String} A file that needs to verify signature.
  • publicKey {String} | {Buffer} | {KeyObject} A valid RSA Public key.
  • signature {String} | {Buffer} Signature.
  • signatureEncoding {String} Signature encoding. default: base64.
  • Returns: {Boolean} true if the verification succeeds, false otherwise.

Verifies the signature against the publicKey using the data from file.

Example

var myVerifyObject = crypto.createVerify('sha256');
var myKey = getPublicKeySomehow();
var mySignature = getSignatureSomehow();

var success = myVerifyObject.verifyFile('./test.txt', myKey, mySignature);
if (!success) {
  throw new Error('Invalid signature!');
}

verify.restart()

Reset the internal state of the verify object, and the verify object can perform update() and verify() operations again.

Sign Object

Sign inherits from stream.Writable class, you can use stream to perform signature operation.

See Verify for examples.

sign.update(data)

  • data {Buffer} | {String} Updates the object with the data. If there is already data in the object, concatenates them.
  • Returns: {Object} This sign object. EdgerOS 1.5.3 and later.

Updates the Sign object with the given data.

sign.sign(privateKey[, passwd[, outputEncoding]])

  • privateKey {String} | {Buffer} | {KeyObject} A valid RSA Private key.
  • passwd {String} Private key password. default: no password.
  • outputEncoding {String} Output encoding. default: buffer object returned.
  • Returns: {String} | {Buffer} Signature string or buffer.

Calculates the signature on all the data passed through using sign.update().

Example

const { privateKey, publicKey } = crypto.generateKeyPair('rsa', {
  modulusLength: 2048,
});

const sign = crypto.createSign('SHA256');
sign.update('111_222_333');
const signature = sign.sign(privateKey, undefined, 'base64');
console.log('Signature:', signature);

const verify = crypto.createVerify('SHA256');
verify.update('111_222_333');
console.log(verify.verify(publicKey, signature));

sign.signFile(file, privateKey[, passwd[, outputEncoding]])

  • file {String} A file that needs to calculate signature.
  • publicKey {String} | {Buffer} | {KeyObject} A valid RSA Public key.
  • passwd {String} Private key password. default: no password.
  • outputEncoding {String} Output encoding. default: buffer object returned.
  • Returns: {String} | {Buffer} Signature string or buffer.

Calculate the signature of the specified file.

sign.restart()

Reset the internal state of the sign object, and the sign object can perform update() and sign() operations again.

Key Object

Functions crypto.createPrivateKey() and crypto.createPublicKey() return KeyObject type objects, this object contains the following properties and methods:

  • asymmetricKeySize {Integer} Asymmetric encryption key bit length.
  • asymmetricKeyType {String} Asymmetric encryption type.
  • type {String} Key type 'private' or 'public'.
  • export {Function} Get Output key string.
  • encrypt {Function} Perform asymmetric encryption.
  • decrypt {Function} Perform asymmetric decryption.

key.export()

  • Returns: {String} Key string in x509 format.

Get key string.

Example

const { publicKey, privateKey } = crypto.generateKeyPair('rsa', { modulusLength: 2048 });

var privkey = crypto.createPrivateKey(privateKey);
console.log(privkey.export());

var pubkey = crypto.createPublicKey(publicKey);
console.log(pubkey.export());

key.encrypt(string)

  • string {String} Content to encryption.
  • Returns: {Buffer} Encrypted data.

Perform asymmetric encryption.

key.encrypt(buffer[, offset[, length]])

  • buffer {Buffer} Data buffer to encryption.
  • offset {Integer} Buffer offset. default:0.
  • length {Integer} Encryption length. default:buffer.length.

Perform asymmetric encryption.

Example

var plaintext = 'test';

// Private Key Encryption
var ciphertext = privkey.encrypt(plaintext);
console.log(ciphertext.toString('hex'));

key.decrypt(buffer[, offset[, length]])

  • buffer {Buffer} Data buffer to decryption.
  • offset {Integer} Buffer offset. default:0.
  • length {Integer} Decryption length. default:buffer.length.

Perform asymmetric decryption.

Example

var plaintext = 'test';

// Private Key Encryption
var ciphertext = privkey.encrypt(plaintext);
console.log(ciphertext.toString('hex'));

// Public Key Decryption
var output = pubkey.decrypt(ciphertext);
console.log(output.toString());

Example

var plaintext = 'test';

// Public Key Encryption
var ciphertext = pubkey.encrypt(plaintext);
console.log(ciphertext.toString('hex'));

// Private Key Decryption
var output = privkey.decrypt(ciphertext);
console.log(output.toString());

key.options(opt)

  • opt {Object} Options.
    • padding {Integer} Padding type.
    • hash {String} Hash type.

Set the key object padding and hash type. Only RSA key objects support this operation. The optional padding includes:

  • crypto.RSA_PKCS_V15 {Integer} Use PKCS#1 v1.5 encoding.
  • crypto.RSA_PKCS_V21 {Integer} Use PKCS#1 v2.1 encoding (OAEP).

Cipher Object

Cipher inherits from stream.Transform class, you can use stream to perform encrypt operation.

Example

const crypto = require('crypto');

const algorithm = 'aes-192-cbc';
const password = 'Password used to generate key';
// Key length is dependent on the algorithm. In this case for aes192, it is
// 24 bytes (192 bits).
const key = crypto.scrypt(password, 'salt', 24);
// Use `crypto.randomBytes()` to generate a random iv instead of the static iv
// shown here.
const iv = Buffer.alloc(16, 0); // Initialization vector.
const cipher = crypto.createCipheriv(algorithm, key, iv);

let encrypted = '';
cipher.on('readable', () => {
  let chunk;
  while (null !== (chunk = cipher.read())) {
    encrypted += chunk.toString('hex');
  }
});
cipher.on('end', () => {
  console.log(encrypted);
  // Prints: e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa
});

cipher.write('some clear text data');
cipher.end();

cipher.final([outputEncoding])

  • outputEncoding {String} Output encoding.
  • Returns: {Buffer} | {String} Any remaining enciphered contents. If outputEncoding is specified, a string is returned. If an outputEncoding is not provided, a Buffer is returned.

Once the cipher.final() method has been called, the Cipher object can no longer be used to encrypt data. Attempts to call cipher.final() more than once will result in an error being thrown.

cipher.update(data[, inputEncoding][, outputEncoding])

  • data {Buffer} | {String} Input data.
  • inputEncoding {String} The encoding of the data.
  • outputEncoding {String} The encoding of the return value.
  • Returns: {Buffer} | {String} If outputEncoding is specified, a string is returned. If an outputEncoding is not provided, a Buffer is returned.

Updates the cipher with data. If the inputEncoding argument is given, the data argument is a string using the specified encoding. If the inputEncoding argument is not given, data must be a Buffer or TypedArray. If data is a Buffer or TypedArray then inputEncoding is ignored.

The outputEncoding specifies the output format of the enciphered data. If the outputEncoding is specified, a string using the specified encoding is returned. If no outputEncoding is provided, a Buffer is returned.

The cipher.update() method can be called multiple times with new data until cipher.final() is called. Calling cipher.update() after cipher.final() will result in an error being thrown.

cipher.setAAD(buffer[, options])

  • buffer {Buffer} Additional authenticated data.
  • options {Object} Not used yet.
  • Returns: {Cipher} for method chaining.

When using an authenticated encryption mode (GCM are currently supported), the cipher.setAAD() method sets the value used for the additional authenticated data (AAD) input parameter.

The cipher.setAAD() method must be called before cipher.update().

cipher.setAutoPadding([autoPadding])

  • autoPadding {Boolean} Auto padding. default: true.
  • Returns: {Cipher} for method chaining.

When using block encryption algorithms, the Cipher class will automatically add padding to the input data to the appropriate block size. To disable the default padding call cipher.setAutoPadding(false).

When autoPadding is false, the length of the entire input data must be a multiple of the cipher's block size or cipher.final() will throw an error. Disabling automatic padding is useful for non-standard padding, for instance using 0x0 instead of PKCS padding.

The cipher.setAutoPadding() method must be called before cipher.final().

cipher.getAuthTag()

  • Returns: {Buffer} When using an authenticated encryption mode (GCM are currently supported), the cipher.getAuthTag() method returns a Buffer containing the authentication tag that has been computed from the given data.

The cipher.getAuthTag() method should only be called after encryption has been completed using the cipher.final() method.

cipher.restart()

Reset the internal state of the cipher object, and the cipher object can perform update() and final() operations again.

Decipher Object

Decipher inherits from stream.Transform class, you can use stream to perform decrypt operation.

Example

const crypto = require('crypto');

const algorithm = 'aes-192-cbc';
const password = 'Password used to generate key';
// Key length is dependent on the algorithm. In this case for aes192, it is
// 24 bytes (192 bits).
// Use the async `crypto.scrypt()` instead.
const key = crypto.scrypt(password, 'salt', 24);
// The IV is usually passed along with the ciphertext.
const iv = Buffer.alloc(16, 0); // Initialization vector.
const decipher = crypto.createDecipheriv(algorithm, key, iv);

let decrypted = '';
decipher.on('readable', () => {
  while (null !== (chunk = decipher.read())) {
    decrypted += chunk.toString('utf8');
  }
});
decipher.on('end', () => {
  console.log(decrypted);
  // Prints: some clear text data
});

// Encrypted with same algorithm, key and iv.
const encrypted =
  'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
decipher.write(encrypted, 'hex');
decipher.end();

decipher.final([outputEncoding])

  • outputEncoding {String} Output encoding.
  • Returns: {Buffer} | {String} Any remaining deciphered contents. If outputEncoding is specified, a string is returned. If an outputEncoding is not provided, a Buffer is returned.

Once the decipher.final() method has been called, the Decipher object can no longer be used to decrypt data. Attempts to call decipher.final() more than once will result in an error being thrown.

decipher.update(data[, inputEncoding][, outputEncoding])

  • data {Buffer} | {String} Input data.
  • inputEncoding {String} The encoding of the data.
  • outputEncoding {String} The encoding of the return value.
  • Returns: {Buffer} | {String} If outputEncoding is specified, a string is returned. If an outputEncoding is not provided, a Buffer is returned.

Updates the decipher with data. If the inputEncoding argument is given, the data argument is a string using the specified encoding. If the inputEncoding argument is not given, data must be a Buffer. If data is a Buffer then inputEncoding is ignored.

The outputEncoding specifies the output format of the enciphered data. If the outputEncoding is specified, a string using the specified encoding is returned. If no outputEncoding is provided, a Buffer is returned.

The decipher.update() method can be called multiple times with new data until decipher.final() is called. Calling decipher.update() after decipher.final() will result in an error being thrown.

decipher.setAAD(buffer[, options])

  • buffer {Buffer} Additional authenticated data.
  • options {Object} Not used yet.
  • Returns: {Decipher} for method chaining.

When using an authenticated encryption mode (GCM are currently supported), the decipher.setAAD() method sets the value used for the additional authenticated data (AAD) input parameter.

The decipher.setAAD() method must be called before decipher.update().

decipher.setAutoPadding([autoPadding])

  • autoPadding {Boolean} Auto padding. default: true.
  • Returns: {Decipher} for method chaining.

When data has been encrypted without standard block padding, calling decipher.setAutoPadding(false) will disable automatic padding to prevent decipher.final() from checking for and removing padding.

Turning auto padding off will only work if the input data's length is a multiple of the ciphers block size.

The decipher.setAutoPadding() method must be called before decipher.final().

decipher.setAuthTag(buffer)

  • buffer {Buffer} Tag data.
  • Returns: {Decipher} for method chaining.

When using an authenticated encryption mode (GCM are currently supported), the decipher.setAuthTag() method is used to pass in the received authentication tag. If no tag is provided, or if the cipher text has been tampered with, decipher.final() will throw, indicating that the cipher text should be discarded due to failed authentication. If the tag length is invalid according to NIST SP 800-38D or does not match the value of the authTagLength option, decipher.setAuthTag() will throw an error.

The decipher.setAuthTag() method must be called before decipher.update() for CCM mode or before decipher.final() for GCM modes. decipher.setAuthTag() can only be called once.

decipher.restart()

Reset the internal state of the decipher object, and the decipher object can perform update() and final() operations again.

Example

const crypto = require('crypto');

const key = 'keykeykeykeykeykeykeykey';
const nonce = crypto.randomBytes(12);
const aad = Buffer.from('0123456789', 'hex');

const cipher = crypto.createCipheriv('aes-192-gcm', key, nonce, {
  authTagLength: 16
});

const plaintext = 'Hello world';
cipher.setAAD(aad, {
  plaintextLength: Buffer.byteLength(plaintext)
});
const ciphertext = cipher.update(plaintext, 'utf8');
cipher.final();
const tag = cipher.getAuthTag();

// Now transmit { ciphertext, nonce, tag }.

const decipher = crypto.createDecipheriv('aes-192-gcm', key, nonce, {
  authTagLength: 16
});

decipher.setAuthTag(tag);
decipher.setAAD(aad, {
  plaintextLength: ciphertext.length
});
const receivedPlaintext = decipher.update(ciphertext, null, 'utf8');

try {
  decipher.final();
} catch (err) {
  console.error('Authentication failed!');
  return;
}

console.log(receivedPlaintext);
文档内容是否对您有所帮助?
有帮助
没帮助